package com.tencent.wxpay.demo.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * IP地址工具类
 */
public class IPUtil {
    /**
     * 获取客户端IPv4地址
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (isBlank(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isBlank(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isBlank(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (isBlank(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (isBlank(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 判断是否是ip v4地址
     * @param ip
     * @return
     */
    private static boolean isBlank(String ip) {
        if (StringUtils.isBlank(ip) || "unkown".equalsIgnoreCase(ip) || ip.split("\\.").length != 4) {
            return true;
        }
        return false;
    }
}
